package demo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ClientFile {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        FileInputStream fis = null;
        InputStream fis2 = null;
        ByteArrayOutputStream baos = null;
        try {
            //1.获取服务器的地址，端口号
            socket = new Socket("127.0.0.1", 9900);
            // 2.创建socket连接获取网络字节输出流
            os = socket.getOutputStream();
            // 3、读取需要上传的文件
            fis = new FileInputStream(new File("6.jpg"));

            //4. 将读取的文件写出，使用字节流
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fis.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }
            //5.通知服务器，我的请求已经结束了，不然会一直等待
            socket.shutdownOutput();
            //6.通知服务器接受完毕，断开连接
            fis2 = socket.getInputStream();
            baos = new ByteArrayOutputStream();
            byte[] bytes2 = new byte[1024];
            int len2;
            while ((len2=fis2.read(bytes2))!= -1){
                baos.write(bytes2,0,len2);
            }
            System.out.println(baos.toString());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //  4.关闭资源
            if (baos != null){

            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
